package com.liit.controller.func;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.liit.annotation.SystemLog;
import com.liit.controller.index.BaseController;
import com.liit.entity.CommodityFormMap;
import com.liit.mapper.CommodityMapper;
import com.liit.plugin.PageView;
import com.liit.upload.UploadUtil;
import com.liit.util.Common;
import com.liit.util.PropertiesUtils;

@Controller
@RequestMapping("/commdoity/")
public class CommodityController extends BaseController {
	@Inject
	private CommodityMapper commodityMapper;
	
	
	@RequestMapping("listCommodity")
	public String listCommodity(Model model) throws Exception {
		model.addAttribute("res", findByRes());
		return Common.BACKGROUND_PATH + "/func/commodity";
	}
	
	@ResponseBody
	@RequestMapping("findCommodityByPage")
	public PageView findCommodityByPage(String pageNow, String pageSize) throws Exception {
		CommodityFormMap commodityFormMap = getFormMap(CommodityFormMap.class);
		Common.trimMap(commodityFormMap);
		commodityFormMap.put("orderby", " order by createTime desc ");
		commodityFormMap = toFormMap(commodityFormMap, pageNow, pageSize, commodityFormMap.getStr("orderby"));
		pageView.setRecords(commodityMapper.findByPage(commodityFormMap));
		return pageView;
	}
	
	
	@RequestMapping("editUI")
	public String editUI(Model model) throws Exception {
		String id = getPara("id");
		if (Common.isNotEmpty(id)) {
			model.addAttribute("commodity", commodityMapper.findbyFrist("id", id, CommodityFormMap.class));
		}
		return Common.BACKGROUND_PATH + "/system/commodity/saveOrUpdate";
	}
	
	/**
	 * 新增或修改礼品信息
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("saveOrUpdate")
	@Transactional(readOnly = false)
	// 需要事务操作必须加入此注解
	@SystemLog(module = "礼品管理", methods = "礼品管理-新增或修改")
	// 凡需要处理业务逻辑的.都需要记录操作日志
	public String saveOrUpdate(HttpServletRequest request,@RequestParam(value="urlName",required=false) MultipartFile urlName,@RequestParam(value="id",required=false)String id,
			@RequestParam(value="name",required=false)String name,@RequestParam(value="property",required=false)String property,
			@RequestParam(value="description",required=false)String description,@RequestParam(value="integralPrice",required=false)String integralPrice,
			@RequestParam(value="money",required=false)String money) throws Exception {
		SimpleDateFormat simple=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		CommodityFormMap commodity = new CommodityFormMap();
		commodity.put("id",id);
		commodity.put("name",name);
		commodity.put("property", property);
		commodity.put("description",description);
		commodity.put("integralPrice",integralPrice);
		commodity.put("money", money);
		String path = PropertiesUtils.findPropertiesKey("file.upload.path");
		path=path+"images/";
		if(urlName.getOriginalFilename()!=null&&!"".equals(urlName.getOriginalFilename())){
			String fName=urlName.getOriginalFilename();
			String prefix=fName.substring(fName.lastIndexOf(".")+1);
			prefix=prefix.toLowerCase();
			String newFileName=String.valueOf(System.currentTimeMillis())+"."+prefix;
			SaveFileFromInputStream(urlName.getInputStream(),path,newFileName);
			commodity.put("images", newFileName);
		}
		if(!"".equals(commodity.get("id"))&&commodity.get("id")!=null){
			commodity.put("accountName",Common.getAccountName());
			commodity.put("updateTime", simple.format(new Date()));
			CommodityFormMap com=commodityMapper.findbyFrist("id", id, CommodityFormMap.class);
			if(urlName.getOriginalFilename()!=null&&!"".equals(urlName.getOriginalFilename())){
				try {
					deleteFile(path+com.getStr("images"));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			commodityMapper.editEntity(commodity);
		}else{
			commodity.put("accountName",Common.getAccountName());
			commodityMapper.addEntity(commodity);
		}
		return "success";
	}
	/**
	 * 删除礼品信息
	 */
	@ResponseBody
	@RequestMapping("deleteEntity")
	@Transactional(readOnly = false)
	// 需要事务操作必须加入此注解
	@SystemLog(module = "礼品管理", methods = "删除礼品")
	// 凡需要处理业务逻辑的.都需要记录操作日志
	public String deleteEntity() throws Exception {
		String[] ids = getPara("ids").split(",");
		for (String id : ids) {
			CommodityFormMap com=commodityMapper.findbyFrist("id",id, CommodityFormMap.class);
			deleteFile(UploadUtil.UPLOAD_PATH + "images"+"/"+com.getStr("images"));
			commodityMapper.deleteByAttribute("id", id, CommodityFormMap.class);
		}
		return "success";
	}
	
	 public void SaveFileFromInputStream(InputStream stream,String path,String filename) throws IOException{    
	 	FileOutputStream fs=new FileOutputStream(path + filename);
        byte[] buffer =new byte[1024*1024];    
        int bytesum = 0;    
        int byteread = 0;     
        while ((byteread=stream.read(buffer))!=-1)    
        {    
           bytesum+=byteread;    
           fs.write(buffer,0,byteread);    
           fs.flush();    
        }     
        fs.close();    
        stream.close();          
	   } 
	 public void deleteFile(String name) throws IOException{
		 File fis =new File(name);
		 fis.delete();
	 }
}
